<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/31
 * Time: 15:57
 */

namespace app\index\logic;


use app\admin\logic\MoneyLogic;
use app\common\utils\Constant;
use app\common\utils\WeChatUtils;
use think\cache\driver\Redis;
use think\Config;
use think\Db;
use think\Exception;

class UserLogic
{
    /**
     * 根据token获取用户信息
     * @param $token
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getUserByToken($token){
        if(empty($token)){
            return array('status'=>0,'error'=>'token不能为空');
        }
        $user_id = $this->getUserIdByToken($token);
        $user = $this->getUserById($user_id);
        if(!$user){
            return array('status'=>0);
        }
        $user['token'] = $token;
        return array('status'=>1,'data'=>$user);
    }

    /**
     * 获取用户信息 通过id
     * @param $user_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getUserById($user_id){
        $user = model('User')
            ->where(array('id'=>$user_id))
            ->field(['username','password', 'salt', 'token','email','loginfailure'], true)
            ->find();
        return $user;
    }

    /**
     * 获取用户id token
     * @param $token
     * @return mixed
     */
    public function getUserIdByToken($token){
        $redis = new Redis();
        $user_id = $redis->get($token);
        return $user_id;
    }

    /**
     * 获取用户信息 通过微信授权code
     * @param $code
     * @return mixed
     */
    public function getUserByCode($code){
        Db::startTrans();
        try {
            if(empty($code)){
                return array('status'=>0,'error'=>'code不能为空');
            }
            $we_chat = Config::get('WeChat');
            $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
            $result = $utils->getHtmlAccessToken($code);
            $userInfo = $utils->getUserInfo($result->access_token, $result->openid);
            $user = $this->saveOrUpdateUser($result->openid, $userInfo);
            $redis = new Redis();
            $token = $this->generateToken($user['open_id'], $user['id']);
            $redis->set($token, $user['id']);
            $user['token'] = $token;
            Db::commit();
            return array('status'=>1,'data'=>$user);
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }



    /**
     * 创建或更新用户信息
     * @param $open_id
     * @param $user_info
     * @return $this|array|false|\PDOStatement|string|\think\Model
     */
    public function saveOrUpdateUser($open_id,$user_info){
        $open_id = $open_id.'';
        $user = model('User')
            ->field(['username','password', 'salt', 'token','email','loginfailure'], true)
            ->where(array('open_id'=>$open_id))
            ->find();
        if(!$user){
            //创建用户
            $user_info = $this->makeUser($user_info);
            $user_info['createtime'] = time();
            $user_info['logintime'] = time();
            $user_info['open_id'] = $open_id;
            $user_info['user_type'] = Constant::USER_TYPE_GENERAL;
            $user = model('User')->create($user_info);
        }else{
            $user_info = $this->makeUser($user_info);
            $user_info['updatetime'] = time();
            $user_info['logintime'] = time();
            $user_info['is_first'] = 0;
            $user->save($user_info);
        }
        return $user;
    }

    public function generateToken($open_id,$user_id){
        return substr(md5(md5($open_id) . 'key' . $user_id.''.time()), 0, 30);
    }

    private function makeUser($userInfo){
        $user = [];
        $userInfo = (array)$userInfo;
        if(isset($userInfo) && isset($userInfo['nickname'])) {
            $user['nickname'] = match_chinese($userInfo['nickname']);
            $user['avatar'] = $userInfo['headimgurl'];
            $sex = $userInfo['sex'] . '';
            $user['sex'] = $sex == '2' ? 1 : 0;
        }
        return $user;
    }

    /**
     * 绑定上级用户
     * @param $last_user_id
     * @param $user_id
     * @return array
     */
    public function bindUser($last_user_id,$user_id){
        Db::startTrans();
        try {
            if(empty($user_id) ||  empty($last_user_id) || $user_id == $last_user_id){
                return array('status' => 2, 'msg' => '请勿非法提交!');
            }
            $count = model('User')->where(array('id' => $last_user_id))->count();
            if ($count == 0) {
                return array('status' => 2, 'msg' => '上级用户不存在!');
            }
            $is_first = model('User')->where(array('id' => $user_id))->value('is_first');
            if($is_first == 0){
                return array('status' => 2, 'msg' => '新用户才能绑定上级!');
            }
            //去掉新用户推广奖励
//            model('User')->where(array('id' => $last_user_id))->setInc('answer_money', 1);
//            model('User')->where(array('id' => $last_user_id))->setInc('history_answer_money', 1);
//            $this->saveMoneyLog($last_user_id,$user_id);
            $update_user['last_one'] = $last_user_id;
            $update_user['is_first'] = 0;
            model('User')->where(array('id' => $user_id))->update($update_user);
            Db::commit();
//            $message_logic = new MessageLogic();
//            $message_logic->sendMessage($last_user_id,Constant::CONFIG_NAME_ANSWER_GOLD_REWARD_NOTICE);
            return array('status'=>1);
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }

    }

    private function saveMoneyLog($user_id,$new_user_id){
        $current_money = model('User')->where(array('id'=>$user_id))->value('answer_money');
        $logic = new MoneyLogic();
        $money = 1;
        $change_type = Constant::CHANGE_TYPE_PROMOTE;
        $in_out_type = Constant::IN_OUT_TYPE_IN;
        $desc = '老用户推广获得挑战卡';
        $money_type = Constant::MONEY_TYPE_CHALLENGE_CARD;
        $logic->saveMoneyLog($money,$current_money,$change_type,
            $in_out_type,$desc,$user_id,$money_type,$new_user_id);
    }


}